<?php

namespace Lib;

class Comment {

    static function getComments() {
        $key = __FUNCTION__ . '/';
        $result = Cache::get($key);
        if ($result === false) {
            $query = '
			SELECT *
			FROM `comment`
			ORDER BY `id` DESC
			';
            $result = Database::selectAll($query);
            Cache::set($key, $result, 10 * 60);
        }
        return $result;
    }

    static function commentsTree($comments) {
        $comm_new = array();

        self::_showTree(0, -1, $comments, $comm_new);
        return $comm_new;
    }

    private static function _showTree($ParentID, $lvl, &$comments, &$comm_new) {
        global $lvl;
        $lvl++;
        unset($result);
        $result = array();
        foreach ($comments as $k => $v) {
            $comments[$k]['level'] = 0;
            if ($v['parent'] == $ParentID)
                $result[] = $v;
        }
        if (count($result) > 0) {
            foreach ($result as $row) {
                $row['level'] = $lvl;
                $comm_new[] = $row;
                $ID1 = $row["id"];
                self::_showTree($ID1, $lvl, $comments, $comm_new);
                $lvl--;
            }
        }
    }

    /**
     * Функция переноса текста
     * @param type $word
     * @param type $maxLength
     * @param type $char
     * @return type
     */
    static function wordwrapText($word, $maxLength = 20, $char = '&shy;<wbr />'){
        return str_replace('  ', ' ', wordwrap(str_replace(' ', '  ', $word), $maxLength, $char, 1));
    }

    static function add($message, $user = 0, $parent = 0) {
        if (empty($message)) {
            return false;
        }
        $id_user = (is_array($user) && isset($user['id'])) ? (int) $user['id'] : max(0, (int) $user);
        $id_parent = max(0, (int) $parent);
        $query = '
		INSERT INTO `comment`
		SET
			`user`=' . (int) $id_user . ',
			`comment`="' . Database::escapeString($message) . '",
			`parent`=' . (int) $id_parent . '
		'; //Все параметры экранированы
        $result = Database::exec($query);
        $id_comment = 0;
        if ($result) {
            Cache::delete('getComments/');
            $id_comment = Database::getLastInsertId();
        }
        return $result ? $id_comment : false;
    }

}

?>
